﻿namespace Ngs.Data
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Data.Objects;
    using System.Linq;
    using Ngs.Data;
    using Ngs.MetaData;

    #endregion

    public class EFStore : IObjectStore, IDisposable
    {
        #region Fields                
        private Func<ObjectContext> ContextFactoryMethod;
        protected ObjectContext Context;
        #endregion

        public EFStore(Func<ObjectContext> contextFactory)
        {
            this.ContextFactoryMethod = contextFactory;
        }

        public bool IsOpen
        {
            get;
            protected set;
        }

        public int CommitChanges()
        {
            return this.Context.SaveChanges();
        }

        public void Close()
        {
            this.Context.Dispose();
            this.Context = null;
            this.IsOpen = false;
        }

        public void Open()
        {
            if (!IsOpen)
            {
                this.Context = this.Context ?? this.ContextFactoryMethod();
                this.IsOpen = true;
            }
        }

        public void Dispose()
        {
            this.Close();
        }
    }
}
